﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace sands
{
    public partial class frmFile : sands.SandsForm
    {
        private DataBase db;
        
        public frmFile()
        {
            ctlDate = new DateTimePicker();
            ctlTuition = new Control();
            cbTuition = new CheckBox();
            InitializeComponent();
            db = DataBase.GetInstance();

            #region list config
            list.AutoGenerateColumns = false;
            list.DataSource = db.Dataset;
            list.DataMember = "uczniowie";

            DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
            col1.HeaderText = "Index";
            col1.DataPropertyName = "Index";           
            list.Columns.Add(col1);

            DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
            col2.HeaderText = "Imię";
            col2.DataPropertyName = "Imie";
            list.Columns.Add(col2);

            DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
            col3.HeaderText = "Nazwisko";
            col3.DataPropertyName = "Nazwisko";
            list.Columns.Add(col3);

            list.Sort(col1, ListSortDirection.Ascending);
            #endregion

            groupBox3.DataBindings.Add("Enabled", cbRate, "Checked");
        }

        private void mnuAdd_Click(object sender, EventArgs e)
        {
            frmAdd frmAdd = new frmAdd();

            frmAdd.Text = "Dodaj ucznia";
            frmAdd.btnOK.Text = "Dodaj";

            if (frmAdd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    db.AddStudent(frmAdd.StudentDetails);
                }
                catch (ConstraintException)
                {
                    MessageBox.Show("blad");
                }
            }
        }

        private void mnuEdit_Click(object sender, EventArgs e)
        {
            frmAdd frmEdit = new frmAdd();

            Student tmp = db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0]));
            frmEdit.StudentDetails = tmp;
            frmEdit.Text = "Edytuj dane ucznia";
            frmEdit.btnOK.Text = "Zmień";
            frmEdit.OldID = tmp.Index;
            //frmEdit.ctlIndex.Enabled = false;

            if (frmEdit.ShowDialog() == DialogResult.OK)
            {
                db.Edit(db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0])),frmEdit.StudentDetails);
            }
        }

        private void mnuDelete_Click(object sender, EventArgs e)
        {
            db.TryRemove(db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0])));
        }

        private void mnuDeposit_Click(object sender, EventArgs e)
        {
            frmDeposit frmDeposit = new frmDeposit();
            frmDeposit.StudentDetails = db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0]));

            if (frmDeposit.ShowDialog() == DialogResult.OK)
            {
                db.AddDeposit(db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0])), new Deposit(frmDeposit.ctlDepositDate.Value.ToShortDateString(), frmDeposit.txtNumber.Text, frmDeposit.txtTitle.Text, frmDeposit.txtValue.Text));
            }
        }

        private void list_SelectionChanged(object sender, EventArgs e)
        {
            if (list.CurrentRow !=null)
            {
                Student st = db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0]));
                this.StudentDetails = st;
                RefreshDepositSchedule(st);
                RefreshDepositHistory(st);
            }
        }

        private void RefreshDepositSchedule(Student student)
        {
            String[,] tmp = student.GetDepositSchedule();
            uint sum = 0;

            depositSchedule.Rows.Clear();

            for(int i = 0; i< tmp.Length/2; ++i)
            {
                depositSchedule.Rows.Add(new String[] {tmp[i,0], tmp[i,1]});
                uint res;
                uint.TryParse(tmp[i,1], NumberStyles.Currency, CultureInfo.CurrentCulture.NumberFormat, out res);
                sum += res;
            }

            depositSchedule.Rows.Add(new String[] {"Razem:", sum.ToString("c0") });
            
            DataGridViewCell cell = new DataGridViewTextBoxCell();
            cell.Style.BackColor = Color.Wheat;
            cell.Style.Font = new Font("Microsoft Sans Serif", (float)8,FontStyle.Bold);

            depositSchedule.Rows[depositSchedule.Rows.Count - 1].DefaultCellStyle = cell.Style;
        }

        private void RefreshDepositHistory(Student student)
        {
            depositHistory.Rows.Clear();
            
            List<Deposit> history = student.GetDepositHistory();
            if (history.Count > 0)
            {
                foreach (Deposit depo in history)
                {
                    depositHistory.Rows.Add(depo.ToStringArray());
                }

                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Style = depositHistory.Rows[depositHistory.Rows.Count - 1].DefaultCellStyle;
                cell.Style.SelectionBackColor = Color.Wheat;
                cell.Style.BackColor = Color.Wheat;
                cell.Style.Font = new Font("Microsoft Sans Serif", (float)8, FontStyle.Bold);

                depositHistory.Rows[depositHistory.Rows.Count - 1].DefaultCellStyle = cell.Style;
            }
        }

        private void frmFile_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (db.Dataset.HasChanges())
            {
                db.TrySave();
            }
        }

        private void mnuRemoveDeposit_Click(object sender, EventArgs e)
        {
            db.TryRemoveLastDeposit(db.GetStudent(((String)((DataRowView)list.CurrentRow.DataBoundItem).Row.ItemArray[0])));
        }

        private void mnuBaseValue_Click(object sender, EventArgs e)
        {
            frmBaseValue frmBase = new frmBaseValue();
            if (db.BaseValue.ToString().Length > 0)
                frmBase.txtValue.Text = db.BaseValue.ToString();
            if (DialogResult.OK == frmBase.ShowDialog())
            {
               db.SetBaseValue(uint.Parse(frmBase.txtValue.Text));
            }

        }

        private void mnuExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Plik tekstowy (*.txt)|*.txt";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                db.ExportPayslips(dlg.FileName);
            }
        }

        private void uczniowieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mnuEdit.Enabled = !db.isEmpty;
            mnuDelete.Enabled = !db.isEmpty;
            mnuAddDeposit.Enabled = !db.isEmpty;
            mnuRemoveDeposit.Enabled = !db.isEmpty;
            mnuExport.Enabled = !db.isEmpty;
        }

        private void wpłatyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            uczniowieToolStripMenuItem_Click(sender, e);
        }

        private void mnuPrintAllDeposits_Click(object sender, EventArgs e)
        {
            PrintTotalDeposits print = new PrintTotalDeposits(DateTime.Now.ToLongDateString(),db.GetAllDeposits());

            PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();
            dlgPrintPreview.Width = 700;
            dlgPrintPreview.Height = 500;
            dlgPrintPreview.Document = print;
            dlgPrintPreview.ShowDialog();
        }

        private void mnuPrintTodaysDeposits_Click(object sender, EventArgs e)
        {
            sands.Forms.frmReportSettings dlgReport = new sands.Forms.frmReportSettings();
            dlgReport.txtNumber.Text = db.ReportNumber;
            if (dlgReport.ShowDialog() == DialogResult.OK)
            {
                db.ReportNumber = dlgReport.txtNumber.Text;
                PrintDaysDeposits print = new PrintDaysDeposits(db.ReportNumber, dlgReport.ctlDate.Value.ToShortDateString(), db.GetTodaysDeposits(dlgReport.ctlDate.Value.ToShortDateString()));

                PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();
                dlgPrintPreview.Width = 700;
                dlgPrintPreview.Height = 500;
                dlgPrintPreview.Document = print;

                dlgPrintPreview.ShowDialog();
            }
        }
    }
}
